<template>
  <div class="add-shift-group">
    <a-page-header class="header" :title="title" @back="goBack">
      <template #extra>
        <a-button type="primary" @click="submit">保存</a-button>
      </template>
    </a-page-header>
    <section class="content">
      <a-form layout="vertical">
        <a-row>
          <a-col :span="16" :offset="4">
            <div class="text-title">基本信息</div>
          </a-col>
          <a-col :span="16" :offset="4" class="mt-10">
            <a-form-item label="排班组名称" v-bind="validateInfos.group_name">
              <a-input
                v-model:value="modelRef.group_name"
                placeholder="请输入排班组名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="16" :offset="4">
            <a-form-item
              label="考勤组主要负责人"
              v-bind="validateInfos.admin_uid"
            >
              <a-space size="large" style="flex-wrap: wrap">
                <template v-if="adminMemberList.user.length">
                  <div v-for="user of adminMemberList.user" :key="user.uid">
                    <a-avatar
                      :src="user.avatar"
                      style="color: #fff; background-color: #2681f3"
                    >
                      <template #icon><UserOutlined /></template>
                    </a-avatar>
                    <span class="ml-10"> {{ user.realname }} </span>
                  </div>
                </template>
                <a-button type="primary" ghost @click="chooseMember(1)">
                  添加
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
          <a-col :span="16" :offset="4">
            <a-form-item label="参加考勤的部门和人员">
              <a-space size="large" style="flex-wrap: wrap">
                <template v-if="userMemberList.department.length">
                  <div
                    v-for="department of userMemberList.department"
                    :key="department.id"
                  >
                    <a-avatar style="color: #fff; background-color: #2681f3">
                      <template #icon><PartitionOutlined /></template>
                    </a-avatar>
                    <span class="ml-10"> {{ department.name }} </span>
                  </div>
                </template>
                <template v-if="userMemberList.user.length">
                  <div v-for="user of userMemberList.user" :key="user.uid">
                    <a-avatar
                      :src="user.avatar"
                      style="color: #fff; background-color: #2681f3"
                    >
                      <template #icon><UserOutlined /></template>
                    </a-avatar>
                    <span class="ml-10"> {{ user.realname }} </span>
                  </div>
                </template>
                <a-button type="primary" ghost @click="chooseMember(2)">
                  添加
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
          <a-col :span="16" :offset="4">
            <div class="text-title">考勤班次</div>
          </a-col>
          <a-col :span="16" :offset="4" class="mt-10">
            <a-form-item label="考勤类型" v-bind="validateInfos.shift_type">
              <a-radio-group
                v-model:value="modelRef.shift_type"
                :disabled="shiftDisabled"
              >
                <a-radio :style="radioStyle" :value="0">
                  <span>固定班制</span>
                  <span class="ml-10 text-grey">
                    （排班组内每位人员的上下班时间一致）
                  </span>
                </a-radio>
                <a-radio :style="radioStyle" :value="1">
                  <span>排班制</span>
                  <span class="ml-10 text-grey">
                    （自定义设置每人的班次，请在保存排班组设置后再进行排班）
                  </span>
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="16" :offset="4">
            <a-form-item label="班次设置" v-if="modelRef.shift_type == 0">
              <a-space>
                <span style="white-space: nowrap">快捷班次设置：</span>
                <div v-if="commonShifts.id">
                  <span class="bold mr-5">{{ commonShifts.shift_name }}</span>
                  <template
                    v-for="(text, index) of commonShifts.time_detail"
                    :key="index"
                  >
                    <span v-if="text.startNextDay">次日</span>
                    <span>{{ text.start }}</span>
                    ~
                    <span v-if="text.endNextDay">次日</span>
                    <span> {{ text.end }} </span>;
                  </template>
                  <a-button
                    class="ml-10"
                    type="link"
                    @click="checkShiftDetail(commonShifts.id)"
                  >
                    详情
                  </a-button>
                  <a-button type="link" @click="chooseShifts(commonShifts.id)">
                    更改
                  </a-button>
                </div>
                <template v-else>
                  <span class="text-grey">未设置</span>
                  <a-button type="link" @click="chooseShifts()">设置</a-button>
                </template>
              </a-space>
              <a-table
                v-if="modelRef.time_detail.length"
                :dataSource="modelRef.time_detail"
                :columns="columns"
                rowKey="key"
                :pagination="false"
                class="mt-10"
                :row-selection="rowSelection"
              >
                <template #bodyCell="{ text, record, index, column }">
                  <template v-if="column.key === 'shift'">
                    <template v-if="text.shift_name">
                      <span>{{ text.shift_name }}：</span>
                      <template
                        v-for="(item, index) of text.time_detail"
                        :key="index"
                      >
                        <span v-if="item.startNextDay">次日</span>
                        <span>{{ item.start }}</span>
                        ~
                        <span v-if="item.endNextDay">次日</span>
                        <span> {{ item.end }} </span>
                        <span v-if="index < text.time_detail.length - 1"
                          >；</span
                        >
                      </template>
                    </template>
                    <span v-else>休息</span>
                  </template>
                  <template v-if="column.key === 'action'">
                    <a-button
                      type="link"
                      v-if="record.shift.id"
                      @click="checkShiftDetail(record.shift.id)"
                    >
                      详情
                    </a-button>
                    <a-button
                      type="link"
                      @click="chooseShifts(record.shift.id, record.key)"
                    >
                      更改
                    </a-button>
                  </template>
                </template>
              </a-table>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </section>
    <ChooseOrgMember
      @request="$utils.commonRequest"
      :visible="chooseMemberVisible"
      :deptDisabled="deptDisabled"
      :getDetail="true"
      :checkedList="checkedMemberList"
      @close="chooseMemberVisible = false"
      @success="chooseMemberSuccess"
    />
    <ChooseShifts
      :visible="chooseShiftsVisible"
      :selectedKeys="selectedKeys"
      :tableKey="tableKey"
      @cancel="chooseShiftsVisible = false"
      @success="chooseShiftsSuccess"
    />
    <AddShift
      :visible="detailVisible"
      :isCheck="true"
      :id="detailId"
      @cancel="detailVisible = false"
    />
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, computed, toRaw } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Form, message } from "ant-design-vue";
import { ChooseOrgMember } from "bl-common-vue3";
import { UserOutlined, PartitionOutlined } from "@ant-design/icons-vue";
import ChooseShifts from "./modules/ChooseShifts.vue";
import AddShift from "./modules/AddShift.vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
const useForm = Form.useForm;

export default defineComponent({
  name: "addCompanyShiftGroup",
  components: {
    ChooseOrgMember,
    ChooseShifts,
    UserOutlined,
    PartitionOutlined,
    AddShift,
  },
  setup() {
    const $router = useRouter();
    const $route = useRoute();
    const state = reactive({
      radioStyle: `display: block; padding: 8px 0`,
      chooseMemberVisible: false,
      chooseMemberType: 1, // 1主负责人 2参加考勤的部门和人员
      deptDisabled: true,
      chooseShiftsVisible: false,
      commonShifts: {},
      selectedKeys: [],
      checkedMemberList: {
        user: [],
        department: [],
      },
      adminMemberList: {
        user: [],
        department: [],
      },
      userMemberList: {
        user: [],
        department: [],
      },
      tableKey: 0,
      selectedRowKeys: [],
      detailVisible: false,
      detailId: 0,
      id: $route.query.id,
      shiftDisabled: false,
    });
    const title = computed(() => (state.id ? "编辑排班组" : "新建排班组"));
    const chooseShifts = (id, key) => {
      state.selectedKeys = id ? [id] : [];
      state.tableKey = key || 0;
      state.chooseShiftsVisible = true;
    };
    const chooseShiftsSuccess = (detail) => {
      if (detail.tableKey) {
        const currentItem = modelRef.time_detail.find(
          (item) => item.key == detail.tableKey
        );
        currentItem.shift = detail.list[0];
        if (!state.selectedRowKeys.includes(detail.tableKey)) {
          state.selectedRowKeys.push(detail.tableKey);
        }
      } else {
        state.commonShifts = detail.list[0];
        getShiftData();
      }
      state.chooseShiftsVisible = false;
    };
    const getShiftData = () => {
      modelRef.time_detail = [];
      state.selectedRowKeys = [];
      for (let i = 1; i < 8; i++) {
        let item = {
          key: i,
          workDay: weekMap[i],
          shift: {},
        };
        modelRef.time_detail.push(item);
        if (i < 6) {
          item.shift = state.commonShifts;
          state.selectedRowKeys.push(i);
        }
      }
    };
    const onShiftTypeChange = () => {
      modelRef.time_detail = [];
      state.commonShifts = {};
    };
    const chooseMember = (type) => {
      state.deptDisabled = type == 1;
      state.chooseMemberType = type;
      state.checkedMemberList =
        type == 1 ? state.adminMemberList : state.userMemberList;
      state.chooseMemberVisible = true;
    };
    const chooseMemberSuccess = (detail) => {
      if (state.chooseMemberType == 1) {
        state.adminMemberList = detail;
        modelRef.admin_uid = state.adminMemberList.user.map((item) => item.uid);
      } else {
        state.userMemberList = detail;
        modelRef.shift_user = {
          user: state.userMemberList.user.map((item) => item.uid),
          department: state.userMemberList.department.map((item) => item.id),
        };
      }
      state.chooseMemberVisible = false;
    };
    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectedRowChange,
    }));
    const onSelectedRowChange = (keys) => {
      if (
        !state.commonShifts.id &&
        keys.length > state.selectedRowKeys.length
      ) {
        chooseShifts(0, keys[keys.length - 1]);
      } else {
        state.selectedRowKeys = keys;
        modelRef.time_detail.forEach((item) => {
          if (keys.includes(item.key)) {
            item.shift = state.commonShifts.id
              ? state.commonShifts
              : item.shift;
          } else {
            item.shift = {};
          }
        });
      }
    };
    const checkShiftDetail = (id) => {
      state.detailId = id || 0;
      state.detailVisible = true;
    };
    const modelRef = reactive({
      group_name: "",
      admin_uid: [],
      shift_user: [],
      shift_type: 0, //排班方式（0固定，1排班，2自由班制）
      time_detail: [],
    });
    const requiredRule = [{ required: true, message: "必填项" }];
    const rulesRef = reactive({
      group_name: requiredRule,
      admin_uid: requiredRule,
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );
    const submit = () => {
      if (modelRef.shift_type == 0 && !modelRef.time_detail.length) {
        message.warning("您还未设置默认排班！");
        return;
      }
      validate().then(() => {
        const params = JSON.parse(JSON.stringify(modelRef));
        if (modelRef.shift_type == 0) {
          const time = params.time_detail.map((item) => ({
            key: item.key,
            workDay: item.workDay,
            shift_id: item.shift.id || 0,
          }));
          params.time_detail = { time };
        } else {
          params.time_detail = {};
        }
        params.needMsg = true;
        let method = "post";
        if (state.id) {
          params.id = state.id;
          method = "put";
        }
        request[method]("/org", "/shift/group", params).then((res) => {
          message.success(res.msg || "操作成功");
          goBack();
        });
      });
    };
    const goBack = () => {
      $router.go(-1);
    };

    const getDetail = () => {
      if (!state.id) {
        return;
      }
      request
        .get("/org", "/shift/group", {
          id: state.id,
        })
        .then((res) => {
          const { detail } = res;
          modelRef.group_name = detail.group_name;
          modelRef.shift_type = detail.shift_type;
          state.adminMemberList.user = detail.admin_users;
          modelRef.admin_uid = state.adminMemberList.user.map(
            (item) => item.uid
          );
          if (detail.shift_user_arr.user || detail.shift_user_arr.department) {
            state.userMemberList = {
              user: detail.shift_user_arr.user || [],
              department: detail.shift_user_arr.department || [],
            };
            modelRef.shift_user = {
              user: state.userMemberList.user.map((item) => item.uid),
              department: state.userMemberList.department.map(
                (item) => item.id
              ),
            };
          }

          if (modelRef.shift_type == 0) {
            modelRef.time_detail = detail.time_detail.time.map((item) => {
              if (item.shift_id != 0) {
                state.selectedRowKeys.push(item.key);
              }
              let shift = detail.time_detail.shift[item.shift_id];
              if (shift) {
                shift.time_detail = utils.getShiftTimeDetail(shift.time_detail);
              }
              return {
                ...item,
                shift: shift || {},
              };
            });
            console.log("------------------", toRaw(modelRef.time_detail));
          } else {
            state.shiftDisabled = true;
          }
        });
    };

    const init = () => {
      getDetail();
    };

    init();
    return {
      modelRef,
      validateInfos,
      columns,
      rowSelection,
      title,
      ...toRefs(state),
      goBack,
      chooseShifts,
      chooseShiftsSuccess,
      onShiftTypeChange,
      submit,
      chooseMember,
      chooseMemberSuccess,
      checkShiftDetail,
    };
  },
});
const columns = [
  {
    title: "工作日",
    dataIndex: "workDay",
    key: "workDay",
  },
  {
    title: "班次",
    dataIndex: "shift",
    key: "shift",
  },
  {
    title: "操作",
    dataIndex: "key",
    key: "action",
  },
];
const weekMap = {
  1: "周一",
  2: "周二",
  3: "周三",
  4: "周四",
  5: "周五",
  6: "周六",
  7: "周日",
};
</script>
<style lang="less" scoped>
.add-shift-group {
  width: 100%;
  height: 100%;
  background: #fff;
  border-left: 1px solid #f1f1f1;
  display: flex;
  flex-direction: column;
  .content {
    flex: 1;
    overflow: hidden auto;
  }
}
</style>
